package com.keffect.effects.staticEffects;

import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;

import com.keffect.effects.StaticEffect;

/**
 * 
 * @author Matias Varela
 *         <p>
 *         Student of Licenciatura en Ciencias de la Computacion, at the
 *         Universidad Nacional del Sur (Argentina).
 *         <p>
 *         project site: http://code.google.com/p/keffect-project/
 * 
 */
public class BackgroundImage extends StaticEffect {

	public static int STRETCH = 0, TILE = 1, NORMAL = 2, FIT = 3;
	protected BufferedImage im, newIm;
	protected int option, repeatX, repeatY;


	public BackgroundImage(BufferedImage im, int option) {
		super();
		this.im = im;
		this.option = option;
	}


	public BackgroundImage(BufferedImage im) {
		this(im, NORMAL);
	}


	@Override
	public void initEffectProperties() {
		getEffectPanel().setOpaque(false);
		switch (option) {
			case 0: // STRETCH
				newIm = scaleImage(im, getEffectPanel().getWidth(), getEffectPanel().getHeight());
				break;
			case 1: // TILE
				newIm = tileImage(im, getEffectPanel().getWidth(), getEffectPanel().getHeight());
				break;
			case 2: // NORMAL
				newIm = im;
				break;
			case 3: // FIT
				newIm = fitImage(im, getEffectPanel().getWidth(), getEffectPanel().getHeight());
				break;
		}

	}


	@Override
	public void doPaintBefore(Graphics2D g) {
		g.drawImage(newIm, 0, 0, newIm.getWidth(), newIm.getHeight(), null);
	}


	@Override
	public void doPaintAfter(Graphics2D g) {
	}


	public BufferedImage scaleImage(BufferedImage img, int width, int height) {
		BufferedImage newImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
		Graphics2D g = newImage.createGraphics();
		try {
			g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);
			g.clearRect(0, 0, width, height);
			g.drawImage(img, 0, 0, width, height, null);
		} finally {
			g.dispose();
		}
		return newImage;
	}


	private BufferedImage fitImage(BufferedImage img, int width, int height) {
		int imgWidth = img.getWidth();
		int imgHeight = img.getHeight();

		if (imgWidth * height < imgHeight * width) {
			width = imgWidth * height / imgHeight;
		} else {
			height = imgHeight * width / imgWidth;
		}
		return scaleImage(img, width, height);
	}


	private BufferedImage tileImage(BufferedImage img, int width, int height) {
		repeatX = width / im.getWidth() + 1;
		repeatY = height / im.getHeight() + 1;

		BufferedImage newImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
		Graphics2D g = newImage.createGraphics();

		for (int x = 0; x < repeatX; x++) {
			for (int y = 0; y < repeatY; y++) {
				g.drawImage(im, x * im.getWidth(), y * im.getHeight(), im.getWidth(), im.getHeight(), null);
			}
		}

		return newImage;
	}
}
